<template>
    <div class="base-page">
        <!-- 列表 -->
        <div class="right" style="margin: 0;" v-if="viewList === true">
            <div class="e-table">
                <div class="top">
                    <div class="left">
                        <div class="left-btn">
                            <el-button type="primary"
                                @click="goAdd"
                                class="btn-greenYellow"
                            >新增</el-button>
                        </div>
                    </div>
                    <div class="search_box">
                        <el-input class="ipt" type="text"
                            placeholder="输入搜索关键字"
                            v-model="searchKey"
                            @select="onSearch"
                            @change="onSearch"
                        ><img src="@/assets/search.png" slot="suffix" @click="onSearch" /></el-input>
                        <div class="adverse">
                            <el-button type="primary">高级搜索</el-button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="e-table"
                :style="{width: rightTableWidth}"
            >
                <el-table
                    class="table"
                    :height="rightTableHeight"
                    :data="tableData"
                    border
                    :cell-class-name="cellClsNm"
                    @selection-change="handleSelectionChange"
                >
                    <el-table-column label="序号" type="index" width="55" fixed> </el-table-column>
                    <el-table-column prop="subcontractorName" label="分包商名称" min-width="200"
                        class-name="blue-column"
                    >
                        <template slot-scope="{ row }">
                            <span @click="onEdit(row)">{{ row.subcontractorName || '无'}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="operator" label="操作人员"> </el-table-column>
                </el-table>
            </div>
            <Pagination
                :total="paginationInfo.total"
                :pageSize.sync="paginationInfo.pageSize"
                :currentPage.sync="paginationInfo.currentPage"
                @currentChange="onCurrentChange"
                @sizeChange="onSizeChange"
            />
        </div>
        <!-- 新增编辑界面 -->
        <div class="right" v-else>
            <div class="e-form">
                <div class="tabs scroll_bar"
                    id="tabs"
                    :style="{width: rightTabsWidth, height: rightTabsHeight, overflow: 'auto'}"
                >
                    <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
                        <el-tab-pane label="单位信息" name="baseInfo" :disabled="clickTabFlag"></el-tab-pane>
                        <el-tab-pane label="人员信息" name="detail" :disabled="clickTabFlag"></el-tab-pane>

                        <div id="baseInfoCon" class="con">
                            <div class="tabs-title" id="baseInfo">单位信息</div>
                            <el-form ref="form" :model="formData" label-width="150px">
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="所属机构：">
                                            {{ formData.orgName }}
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="操作人员：">
                                            {{ formData.operator }}
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="分包单位名称：">
                                            <el-input v-model="formData.subcontractorName" placeholder="请选择分包单位">
                                                <i slot="suffix" class="el-icon-document-copy" @click="onFbUnit"
                                                ></i>
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                        <div id="detailCon" class="con">
                            <div class="tabs-title" id="detail">人员信息</div>
                            <div class="e-table">
                                <div style="margin: 0 0 10px;" v-if="viewList !== 'add'">
                                    <el-button type="primary"
                                        @click="onAddSub"
                                        class="btn-greenYellow"
                                    >新增</el-button>
                                </div>
                                <el-table
                                    class="table"
                                    :data="tableDataShow2"
                                    border
                                    :cell-class-name="cellClsNm"
                                    @selection-change="handleSelectionChangeSub"
                                >
                                    <el-table-column label="序号" type="index" width="55" fixed> </el-table-column>
                                    <el-table-column prop="subcontractorName" label="操作" width="120" fixed
                                        class-name="blue-column"
                                    >
                                        <template slot-scope="{ row }">
                                            <div style="text-align: left;">
                                                <el-upload
                                                    style="display: inline-block; margin: 0 10px 0 0;"
                                                    :action="uploadUrl"
                                                    :data="{
                                                        bucketName,
                                                        relationId,
                                                        orgCode
                                                    }"
                                                    :before-upload="beforeAvatarUpload"
                                                    :accept="accept"
                                                    :show-file-list="false"
                                                    :on-success="attachOnSuccess"
                                                    name="files"
                                                >
                                                    <img src="@/assets/btn/commit.png" @click="onChangeCurrent(row)">
                                                </el-upload>
                                                <i class="el-icon-delete"
                                                    style="font-size: 24px; color: #e9513e;"
                                                    @click="onDelSub(row)"
                                                    title="删除"
                                                ></i>
                                            </div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="name" label="人员名称">
                                        <template slot-scope="{ row }">
                                            <el-input placeholder="请输入人员名称" v-model="row.name"></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="files" label="附件">
                                        <template slot-scope="{ row }">
                                            <span style="display: none">{{ row.files }}</span>
                                            <el-upload class="attach_ls"
                                                :file-list="row.files.filter(item => item.changeType !== -1)"
                                                :on-remove="onDelAttach"
                                            ></el-upload>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </div>
                        </div>
                        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
                    </el-tabs>
                </div>
            </div>
            <div class="footer">
                <div class="right-btn">
                    <el-button type="primary"
                        @click="onSave"
                    >保存</el-button>
                    <el-button type="primary"
                        class="btn-delete"
                        @click="onDel"
                    >删除</el-button>
                    <el-button
                        @click="onCancel"
                    >取消</el-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import Pagination from '@/components/pagination/pagination'
// import { deleterRecordIdAttach } from '@/api/base/system'
// eslint-disable-next-line no-unused-vars
import { partBPersonLs, partBPersonGetById, partBPersonGetLs, partBPersonAdd, partBPersonModify, partBPersonDel, partBListAdd, partBListModify } from '@/api/base/material'
// eslint-disable-next-line no-unused-vars
import { debounce, showLoading, hideLoading, selectDataClient, openAppClient, getUuid } from '@/utils/common'
import { mapMutations, mapState } from 'vuex'
import { ip } from '@/utils/request'
export default {
    components: {
        Pagination,
    },
    computed: {
        ...mapState(['userInfo']),
        orgCode () {
            return this.userInfo.orgInfo.shortCode
        },
        relationId () {
            return this.formData.billId
        },
        tableDataShow2 () {
            return this.tableData2.filter(item => item.changeType !== -1)
        },
        // 列表宽度
        rightTableWidth () {
            return (this.screenWidth - 40) + 'px'
        },
        rightTableHeight () {
            if (this.paginationInfo.total > 0) {
                return this.screenHeight - 170
            } else {
                return this.screenHeight - 118
            }
        },
        // tabs内表格宽度
        rightTabsWidth () {
            return (this.screenWidth - 22) + 'px'
        },
        rightTabsHeight () {
            return (this.screenHeight - 71) + 'px'
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 115 - this.lastConHeight
        },
    },
    data () {
        return {
            viewList: true, // 显示列表还是编辑界面: true 显示列表 false 显示编辑界面
            bucketName: 'base',
            searchKey: '',
            treeData: [],
            selectedData: [],
            selectedDataSub: [],
            curSelectOrg: {
                orgId: '',
                orgName: ''
            },
            paginationInfo: {
                total: 0,
                pageSize: 20,
                currentPage: 1,
            },
            attachTableData: [],
            formData: {},
            tabsName: 'baseInfo',
            tableData: [],
            tableData2: [],
            uploadUrl: ip + '/oss/uploader',
            accept: '.jpg,jpeg,.png,.pdf',
            currentRow: null,
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            idsTop: []
        }
    },
    created () {
        this.getLs()
        // this.getPersonLs()
    },
    mounted () {
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()
        // 获取屏幕宽高
        this.getScreenInfo()
        // 注册滚动事件
        this.registScroll()

        window.addEventListener('resize', debounce(this.getScreenInfo))
    },
    methods: {
        ...mapMutations(['setSelectedInfo']),
        // 获取列表
        async getLs () {
            showLoading()
            try {
                const resData = await partBPersonLs({
                    number: this.searchKey,
                    limit: this.paginationInfo.pageSize,
                    page: this.paginationInfo.currentPage,
                    orgname: this.userInfo.orgInfo.orgName
                })
                this.tableData = resData.list
                this.paginationInfo.total = resData.totalCount
                hideLoading()
            } catch {
                hideLoading()
            }
        },
        onCurrentChange () {
            this.getLs()
        },
        onSizeChange () {
            this.getList()
        },
        // 获取机构可选人员
        async getPersonLs () {
            showLoading()
            try {

                hideLoading()
            } catch {
                hideLoading()
            }
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
        onSearch (e) {
            let searchKey = e
            if (typeof e === 'object') {
                searchKey = this.searchKey
            }
            console.log(searchKey)
        },
        goAdd () {
            this.viewList = 'add'
            this.formData = {
                subcontractorId: '',
                subcontractorName: '',
                operatorId: this.userInfo.userId,
                operator: this.userInfo.userName,
                orgId: this.userInfo.orgInfo.orgId,
                orgName: this.userInfo.orgInfo.orgName
            }
            this.tableData2 = []
            this.$nextTick(() => {
                $('#tabs').scrollTo(0, 0)
            })
        },
        async onEdit ({ billId }) {
            showLoading()
            try {
                // 获取人员信息
                const resData = await partBPersonGetById({
                    id: billId
                })
                // 获取人员明细
                const resData2 = await partBPersonGetLs({
                    id: billId
                })
                this.formData = resData
                this.tableData2 = ('data' in resData2 ? resData2.data : resData2) || []
                this.tableData2.forEach(item => {
                    item.uuid = item.dtlId
                    item.files = item.files || []
                    item.files.forEach(file => {
                        file.name = file.fileName
                        file.url = ''
                    })
                })
                console.log(this.tableData2)
                this.viewList = false
                this.$nextTick(() => {
                    $('#tabs').scrollTo(0, 0)
                })
                hideLoading()
            } catch (error) {
                hideLoading()
            }
        },
        async onSave () {
            this.tableData2.forEach(item => {
                item.dtlId = item.dtlId || ''
            })
            console.log(this.formData, this.tableData2)
            // const a = true
            // if (a) {
            //     return
            // }
            showLoading()
            try {
                if (!this.formData.billId) {
                    await partBPersonAdd(this.formData)
                } else {
                    // 编辑
                    await partBPersonModify(this.formData)
                    // 保存人员信息
                    const personLs = this.tableData2.map(item => {
                        let changeType = item.changeType
                        if (!changeType) {
                            if (item.dtlId) {
                                changeType = 2
                            } else {
                                changeType = 1
                            }
                        }
                        return {
                            billId: this.formData.billId,
                            changeType,
                            dtlId: item.dtlId || '',
                            files: item.files,
                            name: item.name || ''
                        }
                    })
                    await partBListModify(personLs)
                }
                this.getLs()
            } catch (err) {
                console.log(err.message)
                hideLoading()
            }
            this.viewList = true
        },
        onDel () {
            this.clientPop('info', '确定要删除吗？数据删除后不可恢复，请谨慎操作！', async () => {
                // 获取币种设置列表
                showLoading()
                try {
                    await partBPersonDel({
                        id: this.formData.billId
                    }).catch(e => {
                        console.log(e.message)
                        hideLoading()
                    })
                    hideLoading()
                    this.clientPop('suc', '删除成功', () => {
                        this.viewList = true
                        this.getLs()
                    })
                } catch (e) {
                    hideLoading()
                }
            })
        },
        onCancel () {
            this.viewList = true
        },
        // 新增人员
        onAddSub () {
            this.tableData2.push({
                uuid: getUuid(),
                changeType: 1,
                name: '',
                files: []
            })
        },
        // 删除人员
        onDelSub ({ uuid, dtlId }) {
            // 如果是后台已有数据，则标记状态
            if (dtlId) {
                this.clientPop('info', '确定要删除吗？数据删除后不可恢复，请谨慎操作！', () => {
                    const findPersonIndex = this.tableData2.findIndex(item => uuid === item.uuid)
                    const findPerson = this.tableData2[findPersonIndex]
                    findPerson.changeType = -1
                    this.tableData2.splice(findPersonIndex, 1, findPerson)
                })
            } else {
                // 否则直接删除
                const findIndex = this.tableData2.findIndex(item => uuid === item.uuid)
                this.tableData2.splice(findIndex, 1)
            }
        },
        // 选中分包商
        handleSelectionChange (val) {
            this.selectedData = val
        },
        // 选中人员信息
        handleSelectionChangeSub (val) {
            this.selectedDataSub = val
        },
        // 选择分包单位
        onFbUnit () {
            selectDataClient({
                SelectServiceToken: 'GeneralSelectOuter', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id
                Title: '选择分包单位', // 标题
                InitParamsStr: JSON.stringify({
                    type: [0, 1, 2, 3] // 0 分包商   1 供应商   2 往来单位   3 事实外包方
                })
            }).then(val => {
                this.curSelectOrg = val[0]
                this.formData.subcontractorId = val[0].outerId
                this.formData.subcontractorName = val[0].outerName
            })
        },
        onChangeCurrent (row) {
            this.currentRow = row
        },
        //文件大小
        beforeAvatarUpload (file) {
            const isLt2M = file.size / 1024 / 1024 < 20

            if (!isLt2M) {
                this.clientPop('err', '上传文件大小不能超过 20MB！')
            }
            return isLt2M
        },
        attachOnSuccess (response, file, fileList) {
            console.log(response, file, fileList, this.currentRow, this.formData)
            response.data.forEach(item => {
                // 存到数据库的字段
                this.currentRow.files.push({
                    billId: this.formData.billId,
                    changeType: 1,
                    fileName: item.originalObjectName,
                    personnelInformationDtlId: this.formData.dtlId,
                    recordId: item.recordId,
                    name: item.originalObjectName,
                    url: item.objectPath,
                    uuid: this.currentRow.uuid,
                })
            })
        },
        async onDelAttach (file) {
            // 找到分包商人员列表中 对应人员
            const findRow = this.tableData2.find(item => item.uuid === file.uuid)
            // 人员附件列表中 对应附件
            const findFile = findRow.files.find(item => item.recordId === file.recordId)
            // 如果是后台已有附件，则标记删除
            if (findFile.dtlId) {
                findFile.changeType = -1
            } else {
                // 否则直接删除
                const findIndex = findRow.files.findIndex(item => item.recordId === file.recordId)
                findRow.files.splice(findIndex, 1)
            }
        },
        onChangeTab (e) {
            const cur = this.idsTop.find(item => item.name === e.name)
            $('#tabs').scrollTo(cur.top, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('detailCon')) {
                    const lastConHeight = document.getElementById('detailCon').offsetHeight
                    this.lastConHeight = lastConHeight - 18
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        getScreenInfo () {
            let screenWidth = document.documentElement.clientWidth || document.body.clientWidth
            let screenHeight = document.documentElement.clientHeight || document.body.clientHeight
            this.screenWidth = screenWidth
            this.screenHeight = screenHeight
        },
        // 注册右侧tabs区域内滚动时定位
        registScroll () {
            let si = setInterval(() => {
                if (document.getElementById('tabs')) {
                    // 保存所有tabName
                    const arr = ['baseInfo', 'detail']
                    const me = this
                    let $idsTop = []
                    if (!$idsTop[$idsTop.length - 1]) {
                        $idsTop = arr.map(item => {
                            const $item = document.getElementById(item)
                            let itemTop = 0
                            if ($item) {
                                itemTop = $item.offsetTop
                            }
                            return {
                                name: item,
                                top: itemTop
                            }
                        })
                    }
                    this.idsTop = $idsTop

                    $('#tabs').on('scroll', function () {
                        // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
                        if (me.clickTabFlag) {
                            return
                        }

                        const scrollTop = $(this).get(0).scrollTop
                        // 倒序查找
                        let curLocal = 0
                        for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                            let item = $idsTop[i].top
                            if (scrollTop + 3 >= item) {
                                curLocal = i
                                break
                            }
                        }
                        // 设置对应tabName
                        me.tabsName = arr[curLocal]
                    })

                    clearInterval(si)
                    si = null
                }
            }, 100)
        }
    }
}
</script>

<style lang="scss" scoped>
.base-page {
    .right{
        margin: 0;
        .tabs {
            ::v-deep .el-tabs__header {
                left: 12px;
            }

        }
    }
}
::v-deep #seat{
    height: 0px !important;
}

::v-deep #tabs{
    height: 500px !important;
}

::v-deep.el-input__suffix{
    display: flex;
    align-items: center;
}
</style>
